<template>
  <div class="main">
    <div class="fileList">
      <div class="title">
        文件列表
        <hr>
      </div>

      <el-table :data="fileList" border style="width: 360px">
        <el-table-column prop="name" label="文件名" width="150">
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="110">
          <template #default="scope">
            {{ formatSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="downloadFile(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="downloadList">
      <el-divider content-position="left">下载列表</el-divider>
      <div class="downloading" v-for="downloadFile in downloadingFileList">
        <span class="fileName">{{ downloadFile.name }}</span>
        <span class="fileSize">{{ formatSize(downloadFile.size) }}</span>
        <span class="downloadSpeed">{{ downloadFile.downloadSpeed }}</span>

        <div class="progress">
          <span>下载进度：</span>
          <el-progress :text-inside="true" :stroke-width="16" :percentage="downloadFile.downloadPersentage" />

          <span v-if="(downloadFile.downloadPersentage > 0) & (downloadFile.downloadPersentage < 100)">
            <el-button circle @click="changeDownloadStop(downloadFile)">
              <i class="el-icon-video-pause" v-if="downloadFile.downloadingStop == false"></i>
              <i class="el-icon-video-play" v-else></i>
            </el-button>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getFileList, downloadAll } from "@/api/tool/file";
import Bus from "@/utils/bus";

export default {
  name: "FileDownload",
  data() {
    return {
      fileList: [],
      downloadingFileList: [],
    }
  },
  created() {
    this.load();
  },

  methods: {
    load() {
      this.fileList.length = 0;
      getFileList().then((res) => {
        console.log(res);
        this.fileList.push(...res.data.data);
      })
    },

    //换算文件的大小单位
    formatSize(size) {
      let unit;
      let units = [" B", " K", " M", " G"];
      let pointLength = 2;
      while ((unit = units.shift()) && size > 1024) {
        size = size / 1024;
      }
      return ((unit === "B" ? size : size.toFixed(pointLength === undefined ? 2 : pointLength)) + unit);
    },

    //点击暂停下载
    changeDownloadStop(file) {
      file.downloadingStop = !file.downloadingStop;
      if (!file.downloadingStop) {
        this.downloadChunk(1, file);
      }
    },

    //点击下载文件
    downloadFile(file) {
      console.log(file);
      let downloadFile = {};
      downloadFile.size = file.size;
      downloadFile.name = file.name;
      downloadFile.md5 = file.md5;
      downloadFile.fileId = file.fileId;
      downloadFile.downloadingStop = false;
      downloadFile.downloadSpeed = "0 M/s";
      downloadFile.downloadPersentage = 0;
      downloadFile.blobList = [];
      downloadFile.chunkList = [];

      // 初始化时getter/setter要创建全
      this.downloadingFileList.push(downloadFile);
      this.downloadChunk(1, downloadFile);
    },

    //点击下载文件分片
    downloadChunk(index, file) {
      let chunkSize = 1024 * 1024 * 5;
      let chunkTotal = Math.ceil(file.size / chunkSize);

      if (index <= chunkTotal) {
        console.log("下载进度", index);
        let exit = file.chunkList.includes(index);

        if (!exit && !file.downloadingStop) {
          let formData = new FormData();
          formData.append("fileName", file.name);
          formData.append("md5", file.md5);
          formData.append("chunkSize", chunkSize);
          formData.append("index", index);
          formData.append("chunkTotal", chunkTotal);
          if (index * chunkSize >= file.size) {
            chunkSize = file.size - (index - 1) * chunkSize;
            formData.set("chunkSize", chunkSize);
          }
          let startTime = new Date().valueOf();

          console.log("开始下载");
          downloadAll(formData).then((res) => {
            console.log(res);
            // 计算下载速度
            let endTime = new Date().valueOf();
            let timeDif = (endTime - startTime) > 0 ? (endTime - startTime) : 1;
            let speed = 1000 * chunkSize / timeDif;
            console.log(timeDif);
            file.downloadSpeed = this.speedCalc(speed);
            file.downloadPersentage = parseInt((index / chunkTotal) * 100);
            file.chunkList.push(index);

            // const blob = new Blob([res.data]);
            const blob = res.data;
            file.blobList.push(blob);
            // console.log(file.blobList);

            if (index == chunkTotal) {
              console.log(this.downloadingFileList);
              let resBlob = new Blob(file.blobList, {
                type: "application/octet-stream",
              });
              console.log("resb", resBlob);

              let url = window.URL.createObjectURL(resBlob); // 将获取的文件转化为blob格式
              let a = document.createElement("a"); // 此处向下是打开一个储存位置
              a.style.display = "none";
              a.href = url;
              // 下面两行是自己项目需要的处理，总之就是得到下载的文件名（加后缀）即可
              a.setAttribute("download", file.name);
              document.body.appendChild(a);
              a.click(); //点击下载
              document.body.removeChild(a); // 下载完成移除元素
              window.URL.revokeObjectURL(url); // 释放掉blob对象
              return 0;
            }
            this.downloadChunk(index + 1, file);
          });
        } else {
          file.downloadPersentage = parseInt((index / chunkTotal) * 100);
          this.downloadChunk(index + 1, file);
        }
      }
    },

    // 计算下载速度
    speedCalc(speed) {
      let speedFinal = '';
      if (1024 > speed) {
        speedFinal = speed.toString + "b/s";
      } else if (1024 * 1024 >= speed && speed > 1024) {
        speedFinal = (speed / 1024).toFixed(1) + "Kb/s";
      } else if (1024 * 1024 * 1024 >= speed && speed > 1024 * 1024) {
        speedFinal = (speed / (1024 * 1024)).toFixed(1) + "Mb/s";
      } else if ((1024 * 1024 * 1024 * 1024) >= speed && speed > 1024 * 1024 * 1024) {
        speedFinal = (speed / (1024 * 1024 * 1024)).toFixed(1) + "Gb/s";
      } else if (speed > 1024 * 1024 * 1024 * 1024) {
        speedFinal = "大于1.0Tb/s";
      }
      return speedFinal;
    },
  },
}
</script>

<style  scoped>
.main {
  display: flex;
}

.fileList {
  width: 400px;
}

.downloadList {
  width: 400px;
}

.title {
  margin-top: 5px;
  margin-bottom: 5px;
}

.downloading {
  margin-top: 10px;
}

.downloading .fileName {
  margin-left: 40px;
  margin-right: 30px;
}

.downloading .fileSize {
  /* margin-left: 70px; */
  margin-right: 30px;
}

.downloading .progress {
  display: flex;
}

.progress .el-progress {
  /* font-size: 18px; */
  width: 310px;
}
</style>